package com.atguigu.srb.oss.controller;

import com.atguigu.srb.common.exception.BusinessException;
import com.atguigu.srb.common.result.R;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author lwm1435@163.com
 * @date 2022-02-12 10:44
 * @description
 */
@Api(tags = "阿里云文件管理")
@RestController
@RequestMapping("/api/oss/file")
public class FileController {

    @Resource
    private FileService fileService;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public R upload(
            @ApiParam(value = "上传的文件", required = true)
            @RequestParam MultipartFile file,
            @ApiParam(value = "分类的目录", required = true)
            @RequestParam String module){
        try {
            //上传图片，并返回图片在服务器的url
            String uploadUrl = fileService.upload(file.getInputStream(),module,file.getOriginalFilename());

            return R.ok().data("url",uploadUrl).message("文件上传成功");
        } catch (IOException e) {
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
        }
    }

    @ApiOperation("删除OSS文件")
    @DeleteMapping("/remove")
    public R remove(
            @ApiParam(value = "要删除的文件路径", required = true)
            @RequestParam String url){
        fileService.removeFile(url);
        return R.ok().message("删除成功");
    }
}
